package rexsee.core.browser.clazz;

import java.util.ArrayList;

public class History {

	private final ArrayList<HistoryItem> mList = new ArrayList<HistoryItem>();
	private int mCurrentIndex = -1;
	private int mTotalPages = 0;

	public void add(String historyItem) {
		if (historyItem.toLowerCase().trim().startsWith("http://googleads.g.doubleclick.net")) return;
		mTotalPages++;
		if (mList.size() == 0) {
			HistoryItem newItem = new HistoryItem(historyItem);
			mList.add(newItem);
			mCurrentIndex = 0;
			return;
		}
		HistoryItem lastItem = mList.get(mCurrentIndex);
		if (lastItem.getUrl().compareTo(historyItem) == 0) return;
		if (mCurrentIndex != mList.size() - 1) {
			for (int i = mList.size() - 1; i > mCurrentIndex; i--) {
				mList.remove(i);
			}
		}
		HistoryItem newItem = new HistoryItem(historyItem);
		if (lastItem.finishTime > 0 && newItem.startTime - lastItem.finishTime > 1000) {
			mList.add(newItem);
			mCurrentIndex++;
		}
	}
	public int getTotalPages() {
		return mTotalPages;
	}
	public int getSize() {
		return mList.size();
	}
	public int getCurrentIndex() {
		return mCurrentIndex;
	}
	public void setCurrentIndex(int index) {
		mCurrentIndex = index;
	}
	public void setCurrentTitle(String title) {
		getCurrentItem().setTitle(title);
	}

	public HistoryItem getCurrentItem() {
		return (mCurrentIndex < 0) ? new HistoryItem("", "") : mList.get(mCurrentIndex);
	}

	public HistoryItem getItemAtIndex(int index) {
		return mList.get(index);
	}

	public void remove(int index) {
		if (index == mCurrentIndex) return;
		if (mList.remove(index) != null) mCurrentIndex = (index > mCurrentIndex) ? mCurrentIndex : mCurrentIndex - 1;

	}
	public void clear() {
		HistoryItem item = getCurrentItem();
		mList.clear();
		mList.add(item);
		mCurrentIndex = 0;
	}

	public void setCurrentItemScroll(int x, int y) {
		getCurrentItem().setScroll(x, y);
	}

}
